package com.xbongbong.paas.print.helper;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.xbongbong.paas.print.config.FileConfig;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.MD5Util;
import com.xbongbong.pro.config.ProBaseConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * OssHelper
 *
 * @author GuoJun.HU
 * @date 2019/5/29 11:10
 * @since V1.0
 */
@Component
public class OssHelper {

    private static final Logger LOG = LoggerFactory.getLogger(OssHelper.class);

    @Resource
    private ProBaseConfig proBaseConfig;

    /**
     * 内网endPoint
     */
    private String internalEndpointSimple;
    /**
     * 外网
     */
    private String endpointSimple;

    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String runEnvName;
    /**
     * 正式项目名称
     */
    private static final String XBB_DINGTALK = "xbbDingtalk";

    static ClientConfiguration conf = new ClientConfiguration();

    static {
        conf.setConnectionTimeout(10000);
        conf.setSocketTimeout(10000);
        conf.setMaxErrorRetry(0);
    }
    /**
     * 请求客户端
     */
    private OSSClient ossClient;

    @PostConstruct
    private void initFields() {
        internalEndpointSimple = proBaseConfig.getInternalEndpointSimple();
        endpointSimple = proBaseConfig.getEndpointSimple();
        accessKeyId = proBaseConfig.getOssAccessKeyId();
        accessKeySecret = proBaseConfig.getAccessKeySecret();
        accessKeySecret = proBaseConfig.getAccessKeySecret();
        bucketName = proBaseConfig.getBucketName();
        runEnvName = ProBaseConfig.getProjectName();

        String localEnvName = "xbbProLocal";
        //不是本地都用内网
        if (localEnvName.equals(runEnvName)) {
            internalEndpointSimple = endpointSimple;
        }

        /*
         * 一定要在endpoint判断之后
         */
        ossClient = new OSSClient(internalEndpointSimple, accessKeyId, accessKeySecret, conf);
    }


    /**
     * 上传InputStream流
     *
     * @param is  InputStream
     * @param key 文件名
     * @return 创建时间： 2018年5月9日 下午7:49:58
     * 修改时间： 2018年5月9日 下午7:49:58 梁鲁江
     * @author 梁鲁江
     */
    public String putObjectInputStream(InputStream is, String key) {
        if (!XBB_DINGTALK.equals(runEnvName)) {
            key = runEnvName + "/" + key;
        }
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("application/vnd.ms-excel");
        metadata.setContentEncoding("UTF-8");
        try {
            ossClient.putObject(bucketName, key, is, metadata);
        } catch (Exception e) {
            LOG.error("=======OSS upload failure", e);
        }
        String url = "https://" + bucketName + "." + endpointSimple + "/" + key;
        LOG.info(String.format("（%s）存入OSS成功============（%s）",DateTimeUtil.getString(DateTimeUtil.getDate()) ,url));
        return url;
    }


    public String upload2AliyunOss(String corpid, byte[] bytes, String realName, String fileType) throws MalformedURLException {
//        byte[] bytes = toByteArray(filePath);
//        if (bytes == null || bytes.length == 0) {
//            return null;
//        }
        String fileKey = FileConfig.getFileKey(corpid, realName, MD5Util.md5(bytes), fileType);
        return upload(fileKey, bytes);
    }

    public String upload(String key, byte[] imageByte) {

        try {
            long size = imageByte.length;
            InputStream content;
            content =  new ByteArrayInputStream(imageByte);
            putObject(proBaseConfig.getBucketName(), key,content, size);
        } catch (IOException e) {

            e.printStackTrace();
            return "";
        }

        return proBaseConfig.getViewurl() + key;
    }

    public void putObject(String bucketName, String key,
                          InputStream content, long size) throws FileNotFoundException {
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);
        //文件类型
        int lastDotIndex = key.lastIndexOf(".");
        // 上传Object.
        ossClient.putObject(bucketName, key, content, meta);
    }


}
